<!-- 单项选择器下拉组件 -->
<template>
  <!-- 表单添加/编辑模式 -->
  <van-field
    v-if="!readonly"
    v-model="modelValue.text"
    :right-icon="disabled ? 'arrow' : ''"
    readonly
    :is-link="!disabled"
    :required="required"
    name="name"
    :class="{ isDisabled: disabled }"
    :label="labelText"
    :placeholder="labelText"
    @click="clickPicker"
    :rules="[{ required: required, message: message }]"
  />
  <!-- 详情只读模式 -->
  <van-field
    v-else
    readonly
    :label="labelText"
    :placeholder="labelText"
    v-model="modelValue.text"
  />
  <van-popup v-model:show="showPicker" position="bottom">
    <van-picker
      :model-value="[props.value]"
      :columns="columns"
      @confirm="onConfirm"
      @cancel="showPicker = false"
    />
  </van-popup>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'

const props = defineProps({
  // label名称
  labelText: {
    type: String,
    default: '选择器'
  },

  // 选择器下拉选项
  columns: {
    type: Array,
    default: () => [
      { text: '杭州', value: 'Hangzhou' },
      { text: '宁波', value: 'Ningbo' },
      { text: '温州', value: 'Wenzhou' },
      { text: '绍兴', value: 'Shaoxing' },
      { text: '湖州', value: 'Huzhou' }
    ]
  },

  // 是否必填
  required: {
    type: Boolean,
    default: false
  },

  // 提示语
  message: {
    type: String,
    default: '请选择'
  },

  // 双向绑定的值
  value: {
    type: String,
    default: ''
  },

  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  },

  // readonly true 只读模式 false 表单模式
  readonly: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:value'])

watch(
  () => props.value,
  val => {
    let res = props.columns.filter(item => {
      return item.value === val
    })
    modelValue.text = res[0].text
    modelValue.value = res[0].val
  }
)

const showPicker = ref(false)
const modelValue = reactive({
  text: '',
  value: ''
})

const clickPicker = () => {
  if (props.disabled) {
    return
  } else {
    showPicker.value = true
  }
}

const onConfirm = ({ selectedOptions }) => {
  modelValue.text = selectedOptions[0]?.text
  modelValue.value = selectedOptions[0]?.value
  emit('update:value', modelValue.value)
  showPicker.value = false
}
</script>
<style lang="scss" scoped>
.isDisabled {
  :deep(.van-icon) {
    color: #c8c9cc;
  }
  :deep(.van-field__control) {
    color: #c8c9cc;
  }
}
</style>
